﻿/*
Copyright (c) 2010 Lance Ward
This software is licensed under the MIT license, except where otherwise noted.
For complete license details, refer to license.txt
*/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace ADNLib
{
	public static class AnimIO
	{
		public static Animation Load(string fileName)
		{
			Animation mov = new Animation();
			FileStream stream = null;
			XmlSerializer serializer = null;
			XmlReader reader = null;

			try
			{
				serializer = new XmlSerializer(typeof(Animation));

				stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
				reader = new XmlTextReader(stream);

				mov = (Animation)serializer.Deserialize(reader);

				reader.Close();
				stream.Close();
				stream.Dispose();
			}
			catch (Exception ex)
			{
				if (stream != null && reader != null)
				{
					reader.Close();
					stream.Close();
				}
			}

			return mov;
		}

		public static bool Save(string fileName, Animation mov)
		{
			XmlSerializer s = null;
			XmlSerializerNamespaces emptySpace = new XmlSerializerNamespaces();
			emptySpace.Add(String.Empty, String.Empty);
			XmlWriterSettings writerSettings = new XmlWriterSettings();
			writerSettings.Indent = true;
			writerSettings.IndentChars = "\t";
			XmlWriter writer = null;

			try
			{
                //DEBUG for serialization issues
                //s = new XmlSerializer(typeof(MotionPath));
                //s = new XmlSerializer(typeof(Motion));
                //s = new XmlSerializer(typeof(Shape));
                //s = new XmlSerializer(typeof(XObject));
                //s = new XmlSerializer(typeof(Frame));
                //s = new XmlSerializer(typeof(Layer));
				s = new XmlSerializer(typeof(Animation));
				writer = XmlWriter.Create(fileName, writerSettings);
				s.Serialize(writer, mov);
				writer.Close();
			}
			catch(Exception ex)
			{
				if (writer != null) { writer.Close(); }
				return false;
			}

			return true;
		}

        public static object CloneObject(object o)
        {
            //TODO: create Clone for each ObjectType
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, o);
            stream.Seek(0, SeekOrigin.Begin);

            object clone = formatter.Deserialize(stream);

            stream.Close();

            return clone;
        }
	}
}
